package com.shuorikeji.huohuo.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;

import com.bytedance.sdk.djx.DJXSdk;
import com.bytedance.sdk.djx.DJXSdkConfig;
import com.bytedance.sdk.openadsdk.TTAdConfig;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.danikula.videocache.HttpProxyCacheServer;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.KsInitCallback;
import com.kwad.sdk.api.SdkConfig;
import com.qq.e.ads.cfg.MultiProcessFlag;
import com.qq.e.comm.managers.GDTAdSdk;
import com.qq.e.comm.managers.setting.GlobalSetting;
import com.shuorikeji.huohuo.BuildConfig;
import com.shuorikeji.huohuo.common.Constant;
import com.shuorikeji.huohuo.jzvideo.MyFileNameGenerator;
import com.shuorikeji.huohuo.utils.InitUtils;
import com.shuorikeji.huohuo.utils.PreUtils;
import com.shuorikeji.huohuo.utils.UserDataObtainController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

/**
 * @author wxl
 */
public class MyApplication extends Application {

    public static final String APP_ID = "wxdf1b4f06ba2e7793";

    /**
     * 保存所有已创建的Activity
     */
    private static Stack<Activity> activityStack;
    // singleton
    private static MyApplication context = null;

    //App的上下文
    public static Context mContext = null;
    //屏幕宽
    public static int width;
    //屏幕高
    public static int height;
    public static String avatar = "";
    public static String token = "";
    public static String realname = "";
    public static String username = "";
    private static String scheduleId;
    private static String fromUser;
    //所有的activity列表
    private List<Activity> activities;

    public boolean isSDKInit;//SDK是否初始化
    private Handler mainHandler;

    private String hxName;

    private String owId, type;
    private boolean isAgreedPrivate;//是否同意隐私政策，true同意，false不同意
    private HttpProxyCacheServer proxy;

    @Override
    public void onCreate() {
        super.onCreate();

        context = this;
        mContext = this;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
        activities = new ArrayList<>();
        AppManager.initialize(this);
        try {
            isAgreedPrivate = (boolean) PreUtils.get(Constant.IS_AGREE_PRIVATE_RULE, false);
        } catch (Exception e) {
            e.printStackTrace();
            isAgreedPrivate = false;
        }
        if (isAgreedPrivate) {
            //用户同意隐私政策
            initCsjAd();
            initTxAdSdk();
            initKS();
        }
    }

    private void initKS() {
        KsAdSDK.init(mContext, new SdkConfig.Builder().appId(Constant.KS_APP_ID) // 测试aapId，请联系快手平台申请正式AppId，必填
//                .appName(appName) // 测试appName，请填写您应用的名称，非必填
                .showNotification(false) // 是否展示下载通知栏，非必填
                .customController(UserDataObtainController.getInstance()) // 控制SDK获取用户设备信息接口，非必填
                .debug(true).setInitCallback(new KsInitCallback() {
                    @Override
                    public void onSuccess() {
                        KsAdSDK.start();
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        Log.i("wxl", "快手init fail code:" + code + "--msg:" + msg);
                    }
                }).setStartCallback(new KsInitCallback() {
                    @Override
                    public void onSuccess() {
                        Log.i("wxl", "快手start success");
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        Log.i("wxl", "快手start fail msg: " + msg);
                    }
                }).build());
    }

    private void initCsjDj() {
        DJXSdk.init(context, "SDK_Setting_" + Constant.CSJ_APP_ID + ".json", new DJXSdkConfig.Builder()
                .debug(true)
                .build());
        DJXSdk.start((success, msg, err) -> {
            if (success) {
                Log.i("wxl", "短剧初始化成功");
            } else {
                Log.e("wxl", "短剧初始化失败：" + msg);
            }
        });
    }

    private void initCsjAd() {
        // TTAdsdk.init仅进行初始化,不会获取个人信息,如果要展示广告,需要再调用TTAdSdk.start方法
//        TTAdSdk.init(context, buildConfig(context));
//        //setp1.2：启动SDK
//        TTAdSdk.start(new TTAdSdk.Callback() {
//            @Override
//            public void success() {
//                Log.i("wxl", "穿山甲广告success: " + TTAdSdk.isSdkReady());
//                initCsjDj();
//            }
//
//            @Override
//            public void fail(int code, String msg) {
//                Log.i("wxl", "穿山甲广告fail:  code = " + code + " msg = " + msg);
//            }
//        });

        InitUtils.csj(this, new InitUtils.InitCallback() {
            @Override
            public void success() {
                InitUtils.smallVideo(getBaseContext(), new InitUtils.InitCallback() {
                    @Override
                    public void success() {
                        Log.i("wxl", "穿山甲广告success: " + TTAdSdk.isSdkReady());
                    }

                    @Override
                    public void fail(int code, String msg) {
                        Log.i("wxl", "穿山甲广告fail:  code = " + code + " msg = " + msg);
                    }
                });
            }

            @Override
            public void fail(int code, String msg) {
                Log.i("wxl", "穿山甲广告fail:  code = " + code + " msg = " + msg);
            }
        });
    }

    private TTAdConfig buildConfig(Context context) {
        return new TTAdConfig.Builder()
                .appId(Constant.CSJ_APP_ID)//应用ID
                .useMediation(true)//开启聚合功能，默认false
                .supportMultiProcess(true)//开启多进程
                .debug(BuildConfig.DEBUG)
                .build();
    }

    private void initTxAdSdk() {
        Map<String, Boolean> params = new HashMap<>();
        params.put("cell_id", true);//false为关闭粗略地理位置获取，不设置或者设置为true为获取
        GlobalSetting.setAgreeReadPrivacyInfo(params);
        GlobalSetting.setChannel(3);
        /*支持多进程，仅限于和 DownloadService 的不在同一进程的 Activity*/
        MultiProcessFlag.setMultiProcess(false);
        //4.560.1430及以后版本
        GDTAdSdk.initWithoutStart(mContext, Constant.TX_YLH_APP_ID); // 该接口不会采集用户信息
        // 调用initWithoutStart后请尽快调用start，否则可能影响广告填充，造成收入下降
        GDTAdSdk.start(new GDTAdSdk.OnStartListener() {
            @Override
            public void onStartSuccess() {
                // 推荐开发者在onStartSuccess回调后开始拉广告
                Log.d("wxl", "腾讯优量汇开启");
            }

            @Override
            public void onStartFailed(Exception e) {
                Log.e("wxl", "gdt onStartFailed:" + e.toString());
            }
        });
    }

    public void addActivities(Activity a) {
        activities.add(a);
    }

    /**
     * 判断应用是否在前台
     *
     * @param context
     * @return
     */
    public static boolean isForeground(Activity context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }

    /**
     * 判断应用是否在后台运行
     *
     * @param context
     * @param proessName
     * @return
     */
    public static boolean isProessRunning(Context context, String proessName) {

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> lists = am.getRunningAppProcesses();

        for (ActivityManager.RunningAppProcessInfo info : lists) {
            if (info.processName.equals(proessName)) {
                return true;
            }
        }
        return false;
    }

    public static HttpProxyCacheServer getProxy(Context context) {
        MyApplication app = (MyApplication) context.getApplicationContext();
        return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy;
    }

    private HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer.Builder(this)
                .maxCacheSize(1024 * 1024 * 1024)       // 1 Gb for cache
                .fileNameGenerator(new MyFileNameGenerator())
                .build();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // 配置MultiDex(第五步)
        // 将MultiDex注入到项目中

    }

    public static MyApplication getInstance() {
        return context;
    }


    /**
     * Activity被销毁时，从Activities中移除
     */
    public void remove(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }
}
